package org.hot100_3;

import java.util.List;

public class leetcode25 {
    public ListNode reverseKGroup(ListNode head, int k) {

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode list = dummy;

        int size = 0;

        ListNode temp = head;

        //统计链表长度
        while (temp != null) {
            size++;
            temp = temp.next;
        }

        ListNode pre = null;
        ListNode next = null;
        for (int i = size; i >= k; i = i - k) {
            //内部进行翻转
            for (int j = 0; j < k; j++) {
                next = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            //处理每个group之间的关系

            //前一组的end节点
            ListNode preGroupEnd = list;
            //当前组的end节点
            ListNode currGroupEnd = list.next;
            //pre指向当前组的开始节点
            preGroupEnd.next = pre;
            //head指向下一组的开始节点（没有翻转）
            currGroupEnd.next = head;
            //更新list，让list表示前一组的end节点
            list = currGroupEnd;
        }

        return dummy.next;
    }
}
